<?php

class TicketsController extends AppController
{
    # Controller Name to be used
    var $name = 'Tickets';

    # Models to be used
    var $uses = array(
        'User','Project','Branch','Department','Group','Ticket','Attachment','TicketHistory'
    );

    # set the layout to use
    var $layout = 'ticket_layout';

    function  beforeFilter($moduleName = null){
        parent::beforeFilter();
    }

    function index($type = 'get'){

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    if($this->authUser['type'] == 'Staff'){//see ticket by u only
                        $condition_array = array('Ticket.created_by'=>$this->authUser['id'],'Ticket.deleted' => 'n');
                    }
                    elseif($this->authUser['type'] == 'Support'){//See Ticket in ur projects only
                        $user_projects = $this->User->getUserProjectById($this->authUser['id']);
                        $project_ids = array();
                        foreach($user_projects['Project'] as $project){
                            $project_ids[] = $project['id'];
                        }
                        $condition_array = array('Ticket.project_id'=>$project_ids,'Ticket.deleted' => 'n');
                    }
                    else{
                        $condition_array = array('Ticket.deleted' => 'n');
                    }

                    if (!empty($search_query)) {
                        if ($qtype == 'id') {
                            $condition_array = array(
                                'Ticket.id' => $search_query,
                                'Ticket.deleted' => 'n'
                            );
                        }
                    }
                    $contain = array(
                        'Project'=>array('fields' => array('Project.id', 'Project.name')),
                        'Status'=>array('fields' => array('Status.id', 'Status.name','Status.set_end')),
                        'Priority'=>array('fields' => array('Priority.id', 'Priority.name')),
                        'User'=>array('fields' => array('User.id','User.fname','User.mname','User.lname'))
                    );
                    $data_table = $this->Ticket->find('all', array('conditions' => $condition_array, 'contain'=>$contain,'order' => "Ticket.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->Ticket->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $created_dt = $obj['Ticket']['created'];
                            $created_arr = explode(' ',$created_dt);
                            $created = $created_arr[0];
                            $big_dt = date('Y-m-d');
                            $set_end = $obj['Status']['set_end'];
                            if($set_end == 'Closed'){
                                $big_dt = $obj['Ticket']['modified'];
                            }
                            $ret = $this->count_days_between_dates($created, $big_dt);
                            $return_arr[] = array(
                                'id' => $obj['Ticket']['id'],
                                'cell' => array(
                                    $obj['Ticket']['id'],
                                    $obj['Ticket']['subject'],
                                    $obj['User']['fname'].' '.$obj['User']['mname'].' '.$obj['User']['lname'],
                                    $obj['Project']['name'],
                                    $obj['Priority']['name'],
                                    $obj['Status']['name'],
                                    $obj['Ticket']['due_dt'],
                                    $obj['Ticket']['estimated_hrs']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = array('Ticket' => $_POST);
                    if ($_POST['id'] > 0) {
                        $data['Ticket']['modified_by'] = $this->authUser['id'];
                    } else {
                        $data['Ticket']['created_by'] = $this->authUser['id'];
                    }

                    //Assign ticket automatically to project manager
                    $mgr = $this->User->getProjectManagers($_POST['project_id']);
                    if(!empty($mgr)){
                        $data['Ticket']['user_id'] = $mgr[0]['User']['id'];
                    }
                    else{//if there is no project manager , assign to no one until a project manager is found
                        $data['Ticket']['user_id'] =  0;
                    }

                    if ($this->Ticket->save($data['Ticket'])) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->Ticket->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete' :
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Ticket');
                    $result = $modObj->updateAll(
                        array('Ticket.deleted' => "'y'",'Ticket.modified_by' => $this->authUser['id']),
                        array('Ticket.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                break;
            }
        }

        $assign_to_data = $this->getGetAssignToList();
        $assign_to = array();
        foreach($assign_to_data as $dat){
            $assign_to[] = array(
                'id'=>$dat['id'],
                'name'=>$dat['name']
            );
        }

        $status_data = $this->getStatus();
        $status = array();
        foreach($status_data as $dat){
            $status[] = array(
                'id'=>$dat['id'],
                'name'=>$dat['name']
            );
        }

        $projects_data = $this->getProjects();
        $projects = array();
        foreach($projects_data as $dat){
            $projects[] = array(
                'id'=>$dat['id'],
                'name'=>$dat['name']
            );
        }

        $priority_data = $this->getPriorities();
        $priorities = array();
        foreach($priority_data as $dat){
            $priorities[] = array(
                'id'=>$dat['id'],
                'name'=>$dat['name']
            );
        }

        $title_for_layout = 'Tickets';
        $page_description = 'Manage Tickets';
        $this->set(compact('title_for_layout','page_description','assign_to','status','projects','priorities'));
    }


    function createTicketHistory($ticket_id,$first_history=false){
        $ticket_data =  $this->Ticket->find('first',array(
            'conditions'=>array('Ticket.id'=>$ticket_id),
            'recursive'=>-1
        ));
        if($ticket_data){
            $ticket_data['Ticket']['ticket_id'] = $ticket_id;
            unset($ticket_data['Ticket']['id']);
            unset($ticket_data['Ticket']['deleted']);
            if(!$first_history){
                //unset more if not the first history
                unset($ticket_data['Ticket']['subject']);
                unset($ticket_data['Ticket']['project_id']);
                unset($ticket_data['Ticket']['priority_id']);
                unset($ticket_data['Ticket']['due_dt']);
                unset($ticket_data['Ticket']['estimated_hrs']);
                unset($ticket_data['Ticket']['branch_id']);
                unset($ticket_data['Ticket']['department_id']);
                unset($ticket_data['Ticket']['created']);
                unset($ticket_data['Ticket']['created_by']);
            }
            $this->TicketHistory->save($ticket_data['Ticket']);
        }
    }

    function create_ticket(){

        if($this->request->is('post')){
           //debug($this->request->data);
            $upload_file = false;
            $save_raw = $save = $this->request->data;
            if(isset($save_raw['Ticket']['attach'])){
                if(!empty($save_raw['Ticket']['attach']['name'])){
                    $upload_file = true;
                }
            }

            $upload_success = true;
            $file_path = '';
            $file_name = '';
            if($upload_file){
                $upload_info = array(
                    'save_path'=>'files/tickets_attachments/',
                    'folder'=>'tickets_attachments/',
                    'file_name'=>$save_raw['Ticket']['attach']['name'],//$_FILES['uploadfile']['name']
                    'file_type'=>$save_raw['Ticket']['attach']['type'],//$_FILES['uploadfile']['type'];
                    'file_tmp_name'=>$save_raw['Ticket']['attach']['tmp_name'],//$_FILES['uploadfile']['tmp_name']
                    'file_size'=>$save_raw['Ticket']['attach']['size'],//$_FILES['uploadfile']['size']
                    'file_name_prefix'=>''
                );
                $result = $this->uploadFile($upload_info);
                if($result['status']){
                    $file_path =  $result['file_path'];
                    $file_name =  $result['file_name'];
                }
                else{
                    $upload_success = false;
                    $this->Session->setFlash($result['msg']);
                    $this->Session->write('process_error', 'yes');
                }
            }

            if($upload_success){
                if(isset($save['Ticket']['notify_list'])){
                    $list_str = '';
                    foreach($save_raw['Ticket']['notify_list'] as $usr_id){
                        $list_str .= $usr_id.',';
                    }
                    $save['Ticket']['notify_list'] = $list_str;
                }
                if(isset($save['Ticket']['attach'])){
                    unset($save['Ticket']['attach']);
                }

                //Assign ticket automatically to project manager
                $mgr = $this->User->getProjectManagers($save_raw['Ticket']['project_id']);
                if(!empty($mgr)){
                    $save['Ticket']['user_id'] = $mgr[0]['User']['id'];
                }
                else{//if there is no project manager , assign to no one until a project manager is found
                    $save['Ticket']['user_id'] =  0;
                }

                if($upload_file){
                    $save['Attachment'][0]=array(
                        'file_name' => $file_name,
                        'url' => $file_path,
                        'created_by' => $this->Auth->user('id')
                    );
                }

                $res = $this->Ticket->saveAll($save);
                if ($res){
                    //Create an ticket history
                    $this->createTicketHistory($this->Ticket->id,true);

                    //Notify Users Code here
                    if(isset($save_raw['Ticket']['notify_list'])){

                    }

                    $this->Session->setFlash('Ticket has been created!');
                    $this->Session->write('process_error', 'no');
                } else {
                    $this->Session->setFlash('Sorry, Ticket cannot be created!');
                    $this->Session->write('process_error', 'yes');
                }
            }
            $this->redirect(array('action' => 'create_ticket'));
        }

        $default_data = array(
            'ticket_id'=>0,
            'created_by'=>$this->Auth->user('id'),
            'modified_by'=>$this->Auth->user('id'),
            'subject'=>'',
            'assign_to'=>$this->Auth->user('id'),
            'status_id'=>'',
            'project_id'=>'',
            'priority_id'=>'',
            'comments'=>'',
            'due_dt'=>'',
            'estimated_hrs'=>'',
            'branch_id'=>'',
            'department_id'=>''
        );

        $param = null;
        $myself = null;
        if($this->authUser['type'] == 'Staff'){
            $param = 'Manager';
            $myself = $this->authUser['id'];
        }
        $assign_to_data = $this->getGetAssignToList($param,$myself);
        $assign_to = array();
        foreach($assign_to_data as $dat){
            $assign_to[$dat['id']]=$dat['name'];
        }

        $status_data = $this->getStatus();
        $status = array();
        foreach($status_data as $dat){
            $status[$dat['id']]=$dat['name'];
        }

        $projects_data = $this->getProjects();
        $projects = array(''=>'');
        foreach($projects_data as $dat){
            $projects[$dat['id']]=$dat['name'];
        }

        $priority_data = $this->getPriorities();
        $priorities = array();
        foreach($priority_data as $dat){
            $priorities[$dat['id']]=$dat['name'];
        }

        $project_more_data = $this->Project->getWithMoreData();
        $controller = $this;

        $title_for_layout = 'Create New Ticket';
        $page_description = 'Start Creating New Ticket';
        $this->set(compact('title_for_layout','page_description','controller','assign_to','status','projects','priorities','project_more_data','default_data'));
    }



    function update_ticket($ticket_id=null){

        if($this->request->is('post')){
            //debug($this->request->data);
            $upload_file = false;
            $save_raw = $save = $this->request->data;
            if(isset($save_raw['Ticket']['attach'])){
                if(!empty($save_raw['Ticket']['attach']['name'])){
                    $upload_file = true;
                }
            }

            $upload_success = true;
            $file_path = '';
            $file_name = '';
            if($upload_file){
                $upload_info = array(
                    'save_path'=>'files/tickets_attachments/',
                    'folder'=>'tickets_attachments/',
                    'file_name'=>$save_raw['Ticket']['attach']['name'],//$_FILES['uploadfile']['name']
                    'file_type'=>$save_raw['Ticket']['attach']['type'],//$_FILES['uploadfile']['type'];
                    'file_tmp_name'=>$save_raw['Ticket']['attach']['tmp_name'],//$_FILES['uploadfile']['tmp_name']
                    'file_size'=>$save_raw['Ticket']['attach']['size'],//$_FILES['uploadfile']['size']
                    'file_name_prefix'=>''
                );
                $result = $this->uploadFile($upload_info);
                if($result['status']){
                    $file_path =  $result['file_path'];
                    $file_name =  $result['file_name'];
                }
                else{
                    $upload_success = false;
                    $this->Session->setFlash($result['msg']);
                    $this->Session->write('process_error', 'yes');
                }
            }

            if($upload_success){
                if(isset($save['Ticket']['notify_list'])){
                    $list_str = '';
                    foreach($save_raw['Ticket']['notify_list'] as $usr_id){
                        $list_str .= $usr_id.',';
                    }
                    $save['Ticket']['notify_list'] = $list_str;
                }
                if(isset($save['Ticket']['attach'])){
                    unset($save['Ticket']['attach']);
                }

                if($upload_file){
                    $save['Attachment'][0]=array(
                        'file_name' => $file_name,
                        'url' => $file_path,
                        'created_by' => $this->Auth->user('id')
                    );
                }

                $res = $this->Ticket->saveAll($save);
                if ($res){
                    //Create an ticket history
                    $this->createTicketHistory($save_raw['Ticket']['id']);

                    //Notify Users Code here
                    if(isset($save_raw['Ticket']['notify_list'])){

                    }

                    $this->Session->setFlash('Ticket has been updated!');
                    $this->Session->write('process_error', 'no');
                } else {
                    $this->Session->setFlash('Sorry, Ticket cannot be updated!');
                    $this->Session->write('process_error', 'yes');
                }
            }
            $this->redirect(array('action' => 'update_ticket/'.$save_raw['Ticket']['id']));
        }


        $ticket_data = $this->Ticket->find('first',array(
            'conditions'=>array('Ticket.id'=>$ticket_id),
            'contain'=>array(
                'Project'=>array('fields'=>array('Project.id','Project.name')),
                'Priority'=>array('fields'=>array('Priority.id','Priority.name')),
                'Branch'=>array('fields'=>array('Branch.id','Branch.name')),
                'Department'=>array('fields'=>array('Department.id','Department.name'))
            )
         ));
        $ticket_found = false;
        if($ticket_data){
            $ticket_found = true;
        }


        $default_data = array(
            'ticket_id'=>0,
            'creator'=>'',
            'modified_by'=>$this->Auth->user('id'),
            'subject'=>'',
            'assign_to'=>$this->Auth->user('id'),
            'status_id'=>'',
            'project'=>'',
            'priority'=>'',
            'comments'=>'',
            'due_dt'=>'',
            'completion_dt'=>'',
            'estimated_hrs'=>'',
            'actual_hrs'=>'',
            'percentage_complete'=>'',
            'branch'=>'',
            'department'=>''
        );
        if($ticket_found){
            $default_data['ticket_id']=$ticket_id;
            $default_data['subject']=$ticket_data['Ticket']['subject'];
            $default_data['creator']='';
            $default_data['assign_to']=$ticket_data['Ticket']['user_id'];
            $default_data['status_id']=$ticket_data['Ticket']['status_id'];
            $default_data['project']=$ticket_data['Project']['name'];
            $default_data['priority']=$ticket_data['Priority']['name'];
            $default_data['due_dt']=$ticket_data['Ticket']['due_dt'];
            $default_data['estimated_hrs']=$ticket_data['Ticket']['estimated_hrs'];;
            $default_data['branch']=$ticket_data['Branch']['name'];
            $default_data['department']=$ticket_data['Department']['name'];
        }

        $assign_to_data = $this->getGetAssignToList();
        $assign_to = array();
        foreach($assign_to_data as $dat){
            $assign_to[$dat['id']]=$dat['name'];
        }

        $status_data = $this->getStatus();
        $status = array();
        foreach($status_data as $dat){
            $status[$dat['id']]=$dat['name'];
        }

        $ticket_trail = $this->get_ticket_trail($ticket_id);

        //debug($ticket_trail);

        $controller = $this;

        $title_for_layout = 'Update Ticket';
        $page_description = 'Update Existing Ticket';
        $this->set(compact('title_for_layout','page_description','controller','assign_to','status','default_data','ticket_found','ticket_trail'));
    }


    function get_ticket_trail($ticket_id=null){
        $ticket_history_data = $this->TicketHistory->find('all',array(
            'conditions'=>array('TicketHistory.ticket_id'=>$ticket_id),
            'contain'=>array(
                'Status'=>array('fields'=>array('Status.id','Status.name')),
                'Project'=>array('fields'=>array('Project.id','Project.name')),
                'Priority'=>array('fields'=>array('Priority.id','Priority.name')),
                'Branch'=>array('fields'=>array('Branch.id','Branch.name')),
                'Department'=>array('fields'=>array('Department.id','Department.name')),
                'User'=>array('fields'=>array('User.id','User.username','User.fname','User.mname','User.lname'))
            ),
            'order'=>array('TicketHistory.id'=>'asc')
        ));

        $ticket_data = $this->Ticket->find('first',array(
            'conditions'=>array('Ticket.id'=>$ticket_id),
            'contain'=>array(
                'Attachment'=>array('order'=>array('Attachment.id'=>'asc'))
            )
        ));
        $attachments = array();
        if($ticket_data){
            foreach($ticket_data['Attachment']as $att){
                $uploaded_by = $this->User->find('first',array(
                    'fields'=>array('User.id','User.username','User.fname','User.mname','User.lname'),
                    'conditions'=>array('User.id'=>$att['created_by']),
                    'recursive'=>-1
                ));
                $attachments[]=array(
                    'file_name'=>$att['file_name'],
                    'url'=>$att['url'],
                    'uploaded_by'=>$uploaded_by['User']['fname'].' '.$uploaded_by['User']['mname'].' '.$uploaded_by['User']['lname'],
                    'created'=>$att['created']
                );
            }
        }

        //debug($ticket_history_data);

        if($ticket_history_data){
            $return = array();
            foreach($ticket_history_data as $key => $arr){
                $notify_list_arr = explode(',',$arr['TicketHistory']['notify_list']);
                $notify_list_data = $this->User->find('all',array(
                    'fields'=>array('User.id','User.username','User.fname','User.mname','User.lname'),
                    'conditions'=>array('User.id'=>$notify_list_arr),
                    'recursive'=>-1
                ));
                $notify_list = array();
                foreach($notify_list_data as  $arrlist){
                    $notify_list[]= $arrlist['User']['fname'].' '.$arrlist['User']['mname'].' '.$arrlist['User']['lname'];
                }
                $notify_list = implode(',',$notify_list);

                $modified_by = $this->User->find('first',array(
                    'fields'=>array('User.id','User.username','User.fname','User.mname','User.lname'),
                    'conditions'=>array('User.id'=>$arr['TicketHistory']['modified_by']),
                    'recursive'=>-1
                ));

                $inner_arr = array();
                $inner_arr['modified']=$arr['TicketHistory']['modified'];
                $inner_arr['modified_by']=$modified_by['User']['fname'].' '.$modified_by['User']['mname'].' '.$modified_by['User']['lname'];
                if($key != 0){
                    $prev = $ticket_history_data[$key-1];

                    //Compare with previous and determine differences in fields
                    if((!empty($arr['TicketHistory']['completion_dt']))&&($arr['TicketHistory']['completion_dt'] != $prev['TicketHistory']['completion_dt'])){
                        $inner_arr['data']['Completion Date']=$arr['TicketHistory']['completion_dt'];
                    }
                    if((!empty($arr['TicketHistory']['actual_hrs']))&&($arr['TicketHistory']['actual_hrs'] != $prev['TicketHistory']['actual_hrs'])){
                        $inner_arr['data']['Actual Hours']=$arr['TicketHistory']['actual_hrs'];
                    }
                    if((!empty($arr['TicketHistory']['percent_complete']))&&($arr['TicketHistory']['percent_complete'] != $prev['TicketHistory']['percent_complete'])){
                        $inner_arr['data']['Percent Complete']=$arr['TicketHistory']['percent_complete'];
                    }
                    if((!empty($arr['TicketHistory']['status_id']))&&($arr['TicketHistory']['status_id'] != $prev['TicketHistory']['status_id'])){
                        $inner_arr['data']['Status']=$arr['Status']['name'];
                    }
                    if((!empty($arr['TicketHistory']['user_id']))&&($arr['TicketHistory']['user_id'] != $prev['TicketHistory']['user_id'])){
                        $inner_arr['data']['Assign To']=$arr['User']['fname'].' '.$arr['User']['mname'].' '.$arr['User']['lname'];
                    }

                    $inner_arr['data']['Comments']=$arr['TicketHistory']['comments'];
                    if($notify_list){
                        $inner_arr['data']['Notify List']=$notify_list;
                    }
                }
                else{//For the first History Record
                    $created_by = $this->User->find('first',array(
                        'fields'=>array('User.id','User.username','User.fname','User.mname','User.lname'),
                        'conditions'=>array('User.id'=>$arr['TicketHistory']['created_by']),
                        'recursive'=>-1
                    ));
                    $inner_arr['data']['Ticket #']=$arr['TicketHistory']['id'];
                    $inner_arr['data']['Subject']=$arr['TicketHistory']['subject'];
                    $inner_arr['data']['Creator']=$created_by['User']['fname'].' '.$created_by['User']['mname'].' '.$created_by['User']['lname'];
                    $inner_arr['data']['Project']=$arr['Project']['name'];
                    $inner_arr['data']['Priority']=$arr['Priority']['name'];
                    $inner_arr['data']['Status']=$arr['Status']['name'];
                    $inner_arr['data']['Assign To']=$arr['User']['fname'].' '.$arr['User']['mname'].' '.$arr['User']['lname'];
                    $inner_arr['data']['Comments']=$arr['TicketHistory']['comments'];
                    if($notify_list){
                        $inner_arr['data']['Notify List']=$notify_list;
                    }
                    $inner_arr['attachments']=$attachments;
                }
                $return[] = $inner_arr;
            }

            return $return;
        }
        else{
            return false;
        }
    }

    function track_ticket($ticket_id=null){

        $ticket_trail = $this->get_ticket_trail($ticket_id);
        //debug($ticket_data);
        $ticket_found = false;
        if($ticket_trail){
            $ticket_found = true;
        }

        $controller = $this;

        $title_for_layout = 'Ticket History';
        $page_description = 'Ticket History';
        $this->set(compact('title_for_layout','page_description','controller','ticket_found','ticket_trail'));
    }
}